import os
import random

from selenium import webdriver
from selenium.common import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait

from utils.base_util import CommonUtils, Time


class Driver:
    '''
    单例模式
    '''
    __driver = None

    @classmethod
    def get_driver(cls):
        driver_type = CommonUtils.read_ini_by_option('locator/locator.config', 'login', 'browser')
        if (cls.__driver is None) and (hasattr(webdriver, driver_type)):
            cls.__driver = getattr(webdriver, driver_type)()
        cls.__driver.maximize_window()
        return cls.__driver

    @classmethod
    def close_driver(cls):
        cls.__driver.quit()
        cls.__driver = None

class UIUtils:
    @classmethod
    def screenshot(cls):
        '''
        在当前界面截图并保存在i项目下的mg目录
        :return:
        '''
        # 项目的绝对路径
        project_path = CommonUtils.get_project_path()
        # img的绝对路径
        img_path = os.path.join(project_path, "img")
        # 确保img目录存在
        CommonUtils.assure_exist(img_path)
        # 截图的文件名
        time_str = Time.get_format_time("%Y-%m-%d-%H-%M-%S") + ".png"
        # 截图的绝对路径
        pic_path = os.path.join(img_path, time_str)
        driver = Driver.get_driver()
        driver.save_screenshot(pic_path)


class UIAct:
    @classmethod
    def get(cls, url):
        '''
        打开指定的URL
        :return:
        '''
        driver = Driver.get_driver()
        driver.get(url=url)
        driver.maximize_window()

    @classmethod
    def close_browser(cls):
        '''
        关闭标签页并退出关闭浏览器
        :return:
        '''
        driver = Driver.get_driver()
        driver.quit()

    @classmethod
    def get_element(cls, *loc):
        '''
        根据定位数据进行页面元素定位,如果定位到,返回元素(非空),没找到则返回None
        :param loc:
        :return:
        '''
        driver = Driver.get_driver()
        element = None
        try:
            element = WebDriverWait(driver, timeout=10).until(lambda web_driver: web_driver.find_element(*loc))
        except TimeoutException:
            pass
        return element

    @classmethod
    def get_elements(cls, *loc):
        '''
        根据定位数据进行页面元素定位,如果定位到,返回元素(非空),没找到则返回None
        :param loc:
        :return:
        '''
        driver = Driver.get_driver()
        elements = None
        try:
            elements = WebDriverWait(driver, timeout=10).until(lambda web_driver: web_driver.find_elements(*loc))
        except TimeoutException:
            pass
        return elements

    @classmethod
    def input_into_element(cls, element, *data):
        '''
        在指定元素中输入指定的数据
        :param element:
        :param data:
        :return:
        '''
        if element is not None:
            element.click()
            element.clear()
            element.send_keys(*data)

    @classmethod
    def click_element(cls, element):
        '''
        点击指定的元素
        :param element:
        :return:
        '''
        if element is not None:
            element.click()

    @classmethod
    def select_specified(cls, element, option):
        '''
        在指定下拉框中选择指定选项
        :param element:
        :param option:
        :return:
        '''
        if element is not None:
            element = Select(element)
            element.select_by_visible_text(option)

    @classmethod
    def select_random_without_first(cls, element):
        '''
        在指定下拉框中选择第一项以外的任意一项
        :param element:
        :return:
        '''
        if element is not None:
            element = Select(element)
            random_index = random.randint(1,len(element.options)-1)
            element.select_by_index(random_index)

    @classmethod
    def select_random_with_first(cls, element):
        '''
        在指定下拉框中选择任意一项
        :param element:
        :return:
        '''
        if element is not None:
            element = Select(element)
            random_index = random.randint(0,len(element.options)-1)
            element.select_by_index(random_index)

    @classmethod
    def select_random_without_first_and_last(cls, element):
        '''
        在指定下拉框中选择第一项、最后一项以外的任意一项
        :param element:
        :return:
        '''
        if element is not None:
            element = Select(element)
            random_index = random.randint(1, len(element.options) - 2)
            element.select_by_index(random_index)
            return element.options[random_index].text
        return None

    @classmethod
    def locate_element(cls,  location, element_name):
        '''
        定位页面一个元素
        :param location:
        :param element_name:
        :return:
        '''
        by = location[element_name][0]
        by = getattr(By, by)
        value = location[element_name][1]

        element = UIAct.get_element(by, value)
        return element

    @classmethod
    def locate_elements(cls, location, element_name):
        '''
        定位页面多个元素
        :param location:
        :param element_name:
        :return:
        '''
        by = location[element_name][0]
        by = getattr(By, by)
        value = location[element_name][1]

        elements = UIAct.get_elements(by, value)
        return elements

    @classmethod
    def screenshot(cls, vid):  # 会使用  vid代表版本号
        """
        1.判断是否在程序目录下有img目录，如果没有则创建;
        2.生成当前的时间字符串作为图片的名字；将路径和名字拼接起来；
        3.获取driver，使用driver的方法来完成截图操作。
        :return:
        """
        screenshot_path = os.path.join(CommonUtils.get_project_path(), 'report')
        screenshot_path = os.path.join(screenshot_path, str(vid))
        CommonUtils.assure_exist(screenshot_path)
        screenshot_path = os.path.join(screenshot_path, 'img')
        CommonUtils.assure_exist(screenshot_path)
        ctime =Time.get_format_time('%Y%m%d_%H%M%S')
        img_path = os.path.join(screenshot_path, ctime + ".png")
        driver = Driver.get_driver()
        driver.get_screenshot_as_file(img_path)
        img_path = img_path.replace('\\','\\\\')
        return img_path


if __name__ == '__main__':
    # res = Reader.read_ini_by_option('locator/login.config','login','browser')
    # print(type(res))
    # driver = Driver.get_driver()
    # D:\workspace\PycharmProjects\woniuboss\report\4.0\img\20221127_162545.png
    # driver.get('http://www.baidu.com')
    # Driver.close_driver()
    # driver = Driver.get_driver()
    # driver.get('http://www.baidu.com')
    # time.sleep(1)
    # UIUtils.screenshot()
    # Driver.close_driver()
    UIAct.screenshot(4.0)